<?php
/**
 * Author: 孙武 QQ:1228746736
 * Date: 2017/12/1
 * Time: 23:20
 */

namespace wechat;
require_once 'Curl.class.php';

use Curl\Curl;

class WechatTool
{
    private $_appId;
    private $_appSecret;
    private $_tokenSaveName;
    private $_tokenLifeTime;

    /**
     * WechatTool constructor.
     * @param $appid string appid
     * @param $appSecret string appsecret
     * @param string $tokenSavePath token文件保存文件名 如：accessToken.txt
     */
    public function __construct($appid, $appSecret, $tokenSavePath = 'accessToken.txt', $lifeTime = 7000)
    {
        if (strlen($appid) < 6) throw new \Exception('appid错误');
        if (strlen($appSecret) < 6) throw new \Exception('appSecret错误');
        if (strlen($tokenSavePath) < 4) throw new \Exception('tokenSavePath错误');
        if ($lifeTime <= 0) throw new \Exception('lifeTime不能小于0');

        $this->_appId = $appid;
        $this->_appSecret = $appSecret;
        $this->_tokenSaveName = getcwd() . '/' . $tokenSavePath;
        $this->_tokenLifeTime = $lifeTime;
    }

    /**
     * 获取accessToken
     * @param string $accessTokenSavePath accessToken保存地址
     * @return bool|string 成功返回accessToken,失败返回false
     */
    public function getAccessToken()
    {

        $accessToken = file_get_contents($this->_tokenSaveName);
        if (
            file_exists($this->_tokenSaveName) === true &&
            ((time() - filemtime($this->_tokenSaveName)) <= ($this->_tokenLifeTime)) &&
            strlen($accessToken) > 10
        ) {
            //token有效
            return $accessToken;

        } else {
            //无效
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->_appId}&secret={$this->_appSecret}";
            $resData = Curl::curlGetJsonDataByGet($url);
            $errcode=$resData['errcode'];

            if ($errcode > 0) {
                throw new \Exception('获取accessToken错误，请检查appid和appsecret');
            };
            if (strlen($resData['access_token']) < 10) throw new \Exception('获取微信access_token错误，请检查appid和appsecret');
            file_put_contents($this->_tokenSaveName, $resData['access_token']);
            $accessToken=$resData['access_token'];
        }

        if (strlen($accessToken) < 10) throw new \Exception('获取微信access_token错误，请检查保存access_token的文件是否正确');
        return $accessToken;

    }


    /**
     * 首次检查
     * @param string $token
     * @return mixed
     * @throws \Exception
     */
    public function checkSignature($token = 'sunwu')
    {
        //处理信息
        /*
         * 1）将token、timestamp、nonce三个参数进行字典序排序
         * 2）将三个参数字符串拼接成一个字符串进行sha1加密
         * 3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
         * */
        $signature = $_GET['signature'];
        $timestamp = $_GET['timestamp'];
        $nonce = $_GET['nonce'];
        $echostr = $_GET['echostr'];

        //排序处理
        $targetArr = array($token, $timestamp, $nonce);
        sort($targetArr, SORT_STRING);
        $arrStr = implode($targetArr);
        $targetStr = sha1($arrStr);;

        //判断
        if ($targetStr == $signature) {
            echo $echostr;
        } else {
            throw new \Exception('签名错误');
        }
    }
}

function dump($data)
{
    echo "<pre>";
    var_dump($data);
}